#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWidget>
#include <QListWidgetItem>
#include <QIcon>
#include <QSize>
#include <QMessageBox>
#include <QFileDialog>
#include <QRandomGenerator>
#include <QApplication>
#include <QPalette>
#include <QBrush>
#include <QColor>
#include <QDebug>

//构造函数
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    ,m_sceneItem(nullptr)
    ,m_upcloItem(nullptr)
    ,m_downcloItem(nullptr)
    ,m_dressItem(nullptr)
    ,m_shoesItem(nullptr) //初始化成员变量
{
    //设置主窗口的基本属性
    setWindowTitle("服饰搭配工具");
    setMinimumSize(1000,600);

    //初始化界面
    initUI();

    //初始化信号槽连接
    initConnections();

    //加载服饰资源
    loadClothes();

    //设置默认场景
    onScene1BtnClicked();
}
//析构函数
MainWindow::~MainWindow(){}

//初始化界面布局
void MainWindow::initUI()
{
    //创建中心窗口的部件
    QWidget *centralWidget = new QWidget(this);

    //设置主布局为水平布局（三栏布局）
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);

    //将中心部件设置为主窗口的中心部件
    setCentralWidget(centralWidget);

    //====================左侧：服饰便签页===================//
    //创建标签页控件
    QTabWidget* tabWidget = new QTabWidget;

    //1.上衣标签页
    m_upcloList = new QListWidget;
    m_upcloList ->setViewMode(QListWidget::IconMode); //设置为图标模式
    m_upcloList ->setIconSize(QSize(80,80));          //设置图标大小为80*80
    m_upcloList ->setResizeMode(QListWidget::Adjust); //窗口大小变化时自动调整图标布局
    m_upcloList ->setSpacing(10);                       //设置图标间距为10像素
    tabWidget->addTab(m_upcloList,"上衣");            //添加到标签页

    // 2. 下装标签页
    m_downcloList = new QListWidget;
    m_downcloList->setViewMode(QListWidget::IconMode);
    m_downcloList->setIconSize(QSize(80, 80));
    m_downcloList->setResizeMode(QListWidget::Adjust);
    m_downcloList->setSpacing(10);
    tabWidget->addTab(m_downcloList, "下装");

    // 3. 鞋子标签页
    m_shoesList = new QListWidget;
    m_shoesList->setViewMode(QListWidget::IconMode);
    m_shoesList->setIconSize(QSize(80, 80));
    m_shoesList->setResizeMode(QListWidget::Adjust);
    m_shoesList->setSpacing(10);
    tabWidget->addTab(m_shoesList, "鞋子");

    // 4. 连衣裙标签页
    m_dressList = new QListWidget;
    m_dressList->setViewMode(QListWidget::IconMode);
    m_dressList->setIconSize(QSize(80, 80));
    m_dressList->setResizeMode(QListWidget::Adjust);
    m_dressList->setSpacing(10);
    tabWidget->addTab(m_dressList, "连衣裙");

    //将标签页添加到主布局，设置拉伸因子为1（占1/4）
    mainLayout->addWidget(tabWidget,1);

    //===================中间：展示区=====================//
    //创建图形视图
    m_view = new QGraphicsView;
    //创建图形场景
    m_scene = new QGraphicsScene;

    //设置场景大小为400*500像素
    m_scene->setSceneRect(0,0,400,500);

    //将场景设置到视图中
    m_view->setScene(m_scene);

    // 设置视图大小为410×510像素（比场景大10像素，预留边框）
    m_view->setFixedSize(410, 510);

    // 设置背景为白色
    m_view->setBackgroundBrush(Qt::white);

    //使用抗锯齿渲染，使图像更平滑
    m_view->setRenderHint(QPainter::Antialiasing);

    //将视图添加到主布局，设置拉伸因子为2（占2/4宽度）
    mainLayout->addWidget(m_view,2);

    //=================右侧：功能按钮区=================//
    //创建右侧部件和垂直布局
    QWidget* rightWidget = new QWidget;
    QVBoxLayout *rightLayout = new QVBoxLayout(rightWidget);

    //设置按钮间距为20像素
    rightLayout->setSpacing(20);

    // 创建场景切换按钮
    m_scene1Btn = new QPushButton("房间");
    m_scene2Btn = new QPushButton("教室");

    // 创建功能按钮
    m_saveBtn = new QPushButton("保存");
    m_resetBtn = new QPushButton("重置");
    m_randomBtn = new QPushButton("随机");

    // 创建主题切换复选框
    m_themeCheckBox = new QCheckBox("深色主题");

    //将按钮添加到右侧布局
    rightLayout->addWidget(m_scene1Btn);
    rightLayout->addWidget(m_scene2Btn);
    rightLayout->addWidget(m_saveBtn);
    rightLayout->addWidget(m_resetBtn);
    rightLayout->addWidget(m_randomBtn);
    rightLayout->addWidget(m_themeCheckBox);
    // 添加拉伸项，将按钮顶到上方
    rightLayout->addStretch();

    // 将右侧部件添加到主布局，设置拉伸因子为1（占1/4宽度）
    mainLayout->addWidget(rightWidget, 1);
}
//初始化信号槽链接
void MainWindow::initConnections()
{
    //列表项点击事件
    connect(m_upcloList, &QListWidget::itemClicked, this, &MainWindow::onUpListItemClicked);
    connect(m_downcloList, &QListWidget::itemClicked, this, &MainWindow::onDownListItemClicked);
    connect(m_shoesList, &QListWidget::itemClicked, this, &MainWindow::onShoesListItemClicked);
    connect(m_dressList, &QListWidget::itemClicked, this, &MainWindow::onDressListItemClicked);

    //按扭项点击事件
    connect(m_scene1Btn,&QPushButton::clicked,this,&MainWindow::onScene1BtnClicked);
    connect(m_scene2Btn,&QPushButton::clicked,this,&MainWindow::onScene2BtnClicked);
    connect(m_saveBtn,&QPushButton::clicked,this,&MainWindow::onSaveBtnClicked);
    connect(m_saveBtn,&QPushButton::clicked,this,&MainWindow::onSaveBtnClicked);
    connect(m_resetBtn, &QPushButton::clicked, this, &MainWindow::onResetBtnClicked);
    connect(m_randomBtn, &QPushButton::clicked, this, &MainWindow::onRandomBtnClicked);

    //主题切换事件
    connect(m_themeCheckBox,&QCheckBox::toggled,this,&MainWindow::onThemeCheckBoxToggled);
}

    //加载服饰资源到列表
    void MainWindow::loadClothes()
{
        //1.添加上衣
        m_clothesList.append({"白色T恤",":/upclothes/materialPackage/upclothes/T-shirt1.png","上衣", QPoint(0, 0)});
        m_clothesList.append({"粉色T恤",":/upclothes/materialPackage/upclothes/T-shirt3.png","上衣", QPoint(0, 0)});
        m_clothesList.append({"蓝色T恤",":/upclothes/materialPackage/upclothes/T-shirt2.png","上衣", QPoint(0, 0)});
        m_clothesList.append({"黄色T恤",":/upclothes/materialPackage/upclothes/T-shirt4.png","上衣", QPoint(0, 0)});
        m_clothesList.append({"牛仔外套",":/upclothes/materialPackage/upclothes/jacket.png","上衣", QPoint(0, 0)});

        //2.添加下装
        m_clothesList.append({"牛仔裤",":/downclothes/materialPackage/downclothes/trousers1.png","下装", QPoint(0, 150)});
        m_clothesList.append({"运动裤",":/downclothes/materialPackage/downclothes/trousers2.png","下装", QPoint(0, 150)});

        //3.添加连衣裙
        m_clothesList.append({"粉色连衣裙",":/dress/materialPackage/dress/dress1.png","连衣裙", QPoint(0, 0)});
        m_clothesList.append({"蓝色连衣裙",":/dress/materialPackage/dress/dress2.png","连衣裙", QPoint(0, 0)});
        m_clothesList.append({"中式连衣裙",":/dress/materialPackage/dress/dress3.png","连衣裙", QPoint(0, 0)});

        //4.添加鞋子
        m_clothesList.append({"凉鞋",":/shoes/materialPackage/shoes/shoes1.png","鞋子", QPoint(0, 300)});
        m_clothesList.append({"小皮鞋",":/shoes/materialPackage/shoes/shoes2.png","鞋子", QPoint(0, 300)});
        m_clothesList.append({"运动鞋",":/shoes/materialPackage/shoes/shoes3.png","鞋子", QPoint(0, 300)});

        //将服饰添加到对应的列表
        foreach(const ClothesInfo &info, m_clothesList)
        {
            //创建列表项
            QListWidgetItem *item = new QListWidgetItem;

            //尝试加载图片，如果加载失败则使用默认图标
            QPixmap pixmap(info.path);
            if(pixmap.isNull())
            {
                qWarning() << "Failed to load image:" << info.path;
                item->setIcon(QIcon::fromTheme("image-x-generic"));
            }
            else
            {
                item->setIcon(QIcon(pixmap));
            }

            //设置文本（服饰名称）
            item->setText(info.name);
            //设置项大小（比图标略大）
            item->setSizeHint(QSize(100, 100));
            // 根据类别添加到对应列表
             if (info.category == "上衣")
             {
                m_upcloList->addItem(item);
             }
             else if (info.category == "下装")
             {
                m_downcloList->addItem(item);
              }
             else if (info.category == "鞋子")
             {
                  m_shoesList->addItem(item);
             }
             else if (info.category == "连衣裙")
             {
                  m_dressList->addItem(item);
             }

        }

    }

// 清除当前搭配的服饰
void MainWindow::clearCurrentClothes()
{
    // 清除上衣
        if (m_upcloItem)
        {
            m_scene->removeItem(m_upcloItem);
            delete m_upcloItem;
            m_upcloItem = nullptr;
        }

        // 清除下装
        if (m_downcloItem)
        {
            m_scene->removeItem(m_downcloItem);
            delete m_downcloItem;
            m_downcloItem = nullptr;
        }

        // 清除鞋子
        if (m_shoesItem)
        {
            m_scene->removeItem(m_shoesItem);
            delete m_shoesItem;
            m_shoesItem = nullptr;
        }

        // 清除连衣裙
        if (m_dressItem)
        {
            m_scene->removeItem(m_dressItem);
            delete m_dressItem;
            m_dressItem = nullptr;
        }
    }
//添加服饰到场景
void MainWindow::addClothesToScene(const ClothesInfo &info)
{
    // 尝试加载图片
    QPixmap pixmap(info.path);
    if (pixmap.isNull())
    {
        qWarning() << "Failed to load image:" << info.path;
        QMessageBox::warning(this, "加载失败", QString("无法加载服饰图片: %1").arg(info.name));
        return;
    }

    // 创建图形项
    QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);

    // 设置位置（场景中心加上偏移量）
    QPointF center = m_scene->sceneRect().center();
    item->setPos(center.x() - pixmap.width()/2 + info.offset.x(),
                 center.y() - pixmap.height()/2 + info.offset.y());

    // 根据类别添加到场景和对应的成员变量
    if (info.category == "上衣")
    {
        // 先移除旧的上衣
        if (m_upcloItem)
        {
            m_scene->removeItem(m_upcloItem);
            delete m_upcloItem;
        }
        m_upcloItem = item;
        m_scene->addItem(m_upcloItem);
    }
    else if (info.category == "下装")
    {
        // 先移除旧的下装
        if (m_downcloItem)
        {
            m_scene->removeItem(m_downcloItem);
            delete m_downcloItem;
        }
        m_downcloItem = item;
        m_scene->addItem(m_downcloItem);
    }
    else if (info.category == "鞋子")
    {
        // 先移除旧的鞋子
        if (m_shoesItem)
        {
            m_scene->removeItem(m_shoesItem);
            delete m_shoesItem;
        }
        m_shoesItem = item;
        m_scene->addItem(m_shoesItem);
    }
    else if (info.category == "连衣裙")
    {
        // 连衣裙相当于上衣加裤子，所以先移除旧的上衣和下装
        if (m_upcloItem)
        {
            m_scene->removeItem(m_upcloItem);
            delete m_upcloItem;
            m_upcloItem = nullptr;
        }
        if (m_downcloItem)
        {
            m_scene->removeItem(m_downcloItem);
            delete m_downcloItem;
            m_downcloItem = nullptr;
        }
        // 再移除旧的连衣裙
        if (m_dressItem)
        {
            m_scene->removeItem(m_dressItem);
            delete m_dressItem;
        }
        m_dressItem = item;
        m_scene->addItem(m_dressItem);
    }
}

// 根据名称获取服饰信息
ClothesInfo MainWindow::getClothesInfoByName(const QString &name)
{
    foreach (const ClothesInfo &info, m_clothesList)
    {
        if (info.name == name)
        {
            return info;
        }
    }
    // 如果没有找到，返回一个空的服饰信息
    return ClothesInfo();
}

//上衣列表项点击事件处理
void MainWindow::onUpListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }
    //如果当前有连衣裙，先移除
    if(m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }
    //添加到场场景
    addClothesToScene(info);
}

//下装列表项点击事件处理
void MainWindow::onDownListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }
    //如果当前有连衣裙，先移除
    if(m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }
    //添加到场场景
    addClothesToScene(info);
}



//鞋子列表项点击事件处理
void MainWindow::onShoesListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }

    //添加到场场景
    addClothesToScene(info);
}

//连衣裙列表项点击事件处理
void MainWindow::onDressListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }

    //添加到场场景
    addClothesToScene(info);
}

//场景一按钮点击事件处理
void MainWindow::onScene1BtnClicked()
{
    QPixmap pixmap(":/scene/materialPackage/scene/roomscene.png");
    if(pixmap.isNull())
    {
        qWarning()<<"Failed to load roomscene image";
        //如果加载失败，使用默认背景色
        m_view->setBackgroundBrush(Qt::white);

        //移除旧的场景项
        if(m_sceneItem)
        {
            m_scene->removeItem(m_sceneItem);
            delete m_sceneItem;
            m_sceneItem = nullptr;
        }
        return;
    }

    //创建或更新场景项
    if(!m_sceneItem)
    {
        m_sceneItem = new QGraphicsPixmapItem(pixmap);
        m_scene->addItem(m_sceneItem);
    }
    else
    {
        m_sceneItem->setPixmap(pixmap);
    }
    // 设置场景项位置（居中）
    QPointF center = m_scene->sceneRect().center();
    m_sceneItem->setPos(center.x() - pixmap.width()/2,
                         center.y() - pixmap.height()/2);

    // 确保场景项在最底层
    m_sceneItem->setZValue(-1);
}


void MainWindow::onScene2BtnClicked()
{
    QPixmap pixmap(":/scene/materialPackage/scene/schoolscene.png");
    if(pixmap.isNull())
    {
        qWarning()<<"Failed to load schoolscene image";
        //如果加载失败，使用默认背景色
        m_view->setBackgroundBrush(Qt::white);

        //移除旧的场景项
        if(m_sceneItem)
        {
            m_scene->removeItem(m_sceneItem);
            delete m_sceneItem;
            m_sceneItem = nullptr;
        }
        return;
    }

    //创建或更新场景项
    if(!m_sceneItem)
    {
        m_sceneItem = new QGraphicsPixmapItem(pixmap);
        m_scene->addItem(m_sceneItem);
    }
    else
    {
        m_sceneItem->setPixmap(pixmap);
    }
    // 设置场景项位置（居中）
    QPointF center = m_scene->sceneRect().center();
    m_sceneItem->setPos(center.x() - pixmap.width()/2,
                         center.y() - pixmap.height()/2);

    // 确保场景项在最底层
    m_sceneItem->setZValue(-1);
}

//保存按钮
void MainWindow::onSaveBtnClicked()
{
    //获取场景的截图
    QPixmap pixmap = m_view->grab();

    //弹出文件对话框，让用户选择保存路径
    QString fileName = QFileDialog::getSaveFileName(this,
            tr("保存搭配"), "",
            tr("PNG图片 (*.png);;JPEG图片 (*.jpg *.jpeg);;所有文件 (*)"));

        if (fileName.isEmpty())
        {
            return;
        }

        // 保存图片
        if (!pixmap.save(fileName))
        {
            QMessageBox::warning(this, "保存失败", "无法保存图片文件");
        }
        else
        {
            QMessageBox::information(this, "保存成功", QString("图片已保存到: %1").arg(fileName));
        }
}

//重置按钮点击事件处理
void MainWindow::onResetBtnClicked()
{
    //清除当前搭配的服饰
    clearCurrentClothes();

    //重置场景为默认场景
    onScene1BtnClicked();
}

//随机按钮点击事件处理
void MainWindow::onRandomBtnClicked()
{
    //清除当前搭配的服饰
    clearCurrentClothes();

    //获取随机数生成器
    QRandomGenerator* generator = QRandomGenerator::global();

    //随机选择上衣加下装或者连衣裙
    bool chooseDress = (generator->bounded(2) == 0)&&(m_dressList->count()>0);

    if(chooseDress)
    {
        //随机选择连衣裙
        int randomIndex = generator->bounded(m_dressList->count());
        QListWidgetItem *item = m_dressList->item(randomIndex);

        if(item)
        {
            onDressListItemClicked(item);
        }
    }
    else
    {
     // 随机选择上衣（如果有）
      if (m_upcloList->count() > 0)
      {
            int randomIndex = generator->bounded(m_upcloList->count());
             QListWidgetItem *item = m_upcloList->item(randomIndex);
             if (item)
             {
                 onUpListItemClicked(item);
             }


                // 随机选择下装（如果有）
                if (m_downcloList->count() > 0)
                {
                    int randomIndex = generator->bounded(m_downcloList->count());
                    QListWidgetItem *item = m_downcloList->item(randomIndex);
                    if (item)
                    {
                        onDownListItemClicked(item);
                    }
                }
        }
    }
}

//主题切换事件处理
void MainWindow::onThemeCheckBoxToggled(bool checked)
{
    if (checked)
    {
          // 深色主题
            QPalette palette = qApp->palette();
            palette.setColor(QPalette::Window, QColor(53, 53, 53));
            palette.setColor(QPalette::WindowText, Qt::white);
            palette.setColor(QPalette::Base, QColor(25, 25, 25));
            palette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
            palette.setColor(QPalette::ToolTipBase, Qt::white);
            palette.setColor(QPalette::ToolTipText, Qt::white);
            palette.setColor(QPalette::Text, Qt::white);
            palette.setColor(QPalette::Button, QColor(53, 53, 53));
            palette.setColor(QPalette::ButtonText, Qt::white);
            palette.setColor(QPalette::BrightText, Qt::red);
            palette.setColor(QPalette::Link, QColor(42, 130, 218));
            palette.setColor(QPalette::Highlight, QColor(42, 130, 218));
            palette.setColor(QPalette::HighlightedText, Qt::black);
            qApp->setPalette(palette);
      }
    else
    {
            // 浅色主题（默认）
            qApp->setPalette(qApp->style()->standardPalette());
    }
}
